<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">库存查询</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">查询信息</text>
      </view>
      <view class="info-form">
        <view class="form-item">
          <text class="form-label">查询日期</text>
          <text class="warehouse-display">{{ formData.currentDate }}</text>
        </view>
        <view class="form-item">
          <text class="form-label">仓库</text>
          <text class="warehouse-display">{{
            currentWarehouse ? currentWarehouse.warehouseName : "请选择"
          }}</text>
        </view>
      </view>
    </view>

    <!-- C. 查询/选择区 -->
    <view class="search-section">
      <view class="section-header">
        <text class="section-title">查询条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="
              handleTimeChange('today');
              handleSearch();
            "
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="
              handleTimeChange('week');
              handleSearch();
            "
          >
            本周
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'month' }"
            @tap="
              handleTimeChange('month');
              handleSearch();
            "
          >
            本月
          </button>
        </view>
      </view>
      <view class="scan-input-group">
        <view class="input-row">
          <input
            v-model="materialName"
            class="material-input"
            placeholder="请输入物料名称"
            @confirm="handleSearch"
          />
          <button class="search-btn" @tap="handleSearch">搜索</button>
        </view>
      </view>
    </view>

    <!-- D. 列表 -->
    <view class="material-table-section" v-if="detialTableData.length">
      <view class="section-header">
        <text class="section-title">入库记录</text>
      </view>
      <scroll-view class="table-scroll" scroll-y @scrolltolower="onReachBottom">
        <view class="table-row header">
          <text class="header-cell">单据编号</text>
          <text class="header-cell">入库日期</text>
          <text class="header-cell">物料编码</text>
          <text class="header-cell">物料名称</text>
          //钢种
          <text class="header-cell">钢种</text>
          <text class="header-cell">规格</text>
          <text class="header-cell">重量(kg)</text>
          <text class="header-cell">数量(件)</text>
        </view>
        <view
          v-for="(item, index) in detialTableData"
          :key="index"
          class="table-row"
          :class="{ selected: selectedId === item.id }"
        >
          <text class="table-cell">{{ item.realNo }}</text>
          <text class="table-cell">{{ item.inDate }}</text>
          <text class="table-cell">{{ item.materialCode }}</text>
          <text class="table-cell">{{ item.materialName }}</text>
          <text class="table-cell">{{ item.steelGradeName }}</text>
          <text class="table-cell">{{ item.spec || "-" }}</text>
          <text class="table-cell">{{ item.prodCount }}</text>
          <text class="table-cell">{{ item.transCount }}</text>
          <!-- <view class="table-cell">
            <button class="remove-btn-small" @tap="handleReverse(item)">
              红冲
            </button>
          </view> -->
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { queryStockInDetail } from "@/api/warehouse/stockIn";
import { inventoryApi } from "@/api/warehouse/inventory";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
export default {
  name: "InventoryQuery",
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        outType: "领料出库",
        warehouseCode: "",
        warehouseName: "",
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },
      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
      },
      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },
      // 物料名称搜索
      materialName: "",
      // 表格数据
      detialTableData: [],
      detailLoading: false,
      // 加载状态
      loading: false,
      // 分页与刷新
      refreshing: false,
      pageNum: 1,
      hasMore: true,

      // 选中记录
      selectedId: null,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
  },
  onLoad() {
    this.loadCurrentWarehouse();
  },
  methods: {
    /* 加载当前仓库 */
    loadCurrentWarehouse() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.wmName) {
        this.currentWarehouse = {
          warehouseCode: userConfig.wmCode || "DEFAULT",
          warehouseName: userConfig.wmName,
        };
        this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
        this.formData.warehouseName = this.currentWarehouse.warehouseName;
      }
    },

    /* 下拉刷新 = 重置 */
    onPullDownRefresh() {
      this.selectedId = null;
      this.detailTableData = [];
      this.timeRange = {
        startTime: "",
        endTime: "",
      };
      this.refreshing = true;
      setTimeout(() => {
        this.refreshing = false;
      }, 500);
      this.handleSearch();
    },
    /* 触底加载 */
    onReachBottom() {
      if (this.mainLoading) return;
      this.handleSearch(true);
    },
    /* 搜索主表 */
    async handleSearch(loadMore = false) {
      if (!loadMore) this.detailTableData = [];
      this.loading = true;

      // 构建查询参数
      const params = {
        pageNum: this.pageNum,
        pageSize: 10,
        materialName: this.searchForm.materialName || "",
        materialCode: this.searchForm.materialCode || "",
        warehouseName: this.currentWarehouse.warehouseName || "",
      };
      // 只有在时间范围有效时才添加时间参数
      if (this.timeRange.startTime && this.timeRange.endTime) {
        params.createTime = [this.timeRange.startTime, this.timeRange.endTime];
      }

      try {
        const response = await inventoryApi.queryInventory(params);
        if (response.success) {
          this.detialTableData.push(...response.data);
          this.hasMore = response.data.length === 10;
        } else {
          uni.showToast({
            title: response.message || "加载数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      setTimeout(() => {
        this.loading = false;
      }, 600);
    },
    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";
</style>
